<script>
import ManageUpload from '../components/ManageUpload.vue';
import CompositionItem from '../components/CompositionItem.vue';
import { songsCollection, auth } from '../includes/firebase';

export default {
  name: 'ManageSong',
  components: {
    ManageUpload,
    CompositionItem,
  },
  data() {
    return {
      songs: [],
      unsavedFlag: false,
    };
  },
  async created() {
    const snapshot = await songsCollection
      .where('uid', '==', auth.currentUser.uid)
      .get();

    snapshot.forEach(this.addSong);
  },
  methods: {
    updateSong(i, values) {
      this.songs[i].modified_name = values.modified_name;
      this.songs[i].genre = values.genre;
    },
    removeSong(i) {
      this.songs.splice(i, 1);
    },
    addSong(document) {
      const song = {
        ...document.data(),
        docID: document.id,
      };

      this.songs.push(song);
    },
    updatedUnsavedFlag(value) {
      this.unsavedFlag = value;
    },
  },
  beforeRouteLeave(to, from, next) {
    if (!this.unsavedFlag) {
      next();
    } else {
      // eslint-disable-next-line no-restricted-globals,no-alert
      const leave = confirm('You have unsaved changes, Are you sure you want to leave?');
      next(leave);
    }
  },
};
</script>

<template>
  <section class="container mx-auto mt-6">
    <div class="md:grid md:grid-cols-3 md:gap-4">
      <div class="col-span-1">
        <manage-upload  ref="upload" :addSong="addSong" />
      </div>
      <div class="col-span-2">
        <div class="bg-white rounded border border-gray-200 relative flex flex-col">
          <div class="px-6 pt-6 pb-5 font-bold border-b border-gray-200">
            <span class="card-title">我的音乐</span>
            <i class="fa fa-compact-disc float-right text-green-400 text-2xl"></i>
          </div>
          <div class="p-6">
            <composition-item v-for="(song, i) in songs"
                              :key="song.docID"
                              :song="song"
                              :updateSong="updateSong"
                              :index="i"
                              :removeSong="removeSong"
                              :updateUnsavedFlag="updatedUnsavedFlag"
            />
          </div>
        </div>
      </div>
    </div>
  </section>
</template>
